//SQLite.js
import React, {Component} from 'react';
import SQLiteStorage from 'react-native-sqlite-storage';
import Log from './Log'

// SQLiteStorage.enablePromise(true);
SQLiteStorage.DEBUG(true);
// database_name: "/sdcard/TabletPromo/Promo.db",//数据库文件

export const BookDB = {
    database_name: "test12.db",//数据库文件
    database_version: "1",//版本号
    database_displayname: "MySQLite",
    database_size: -1,//-1应该是表示无限制
    db: null,
    table0: {
        name: 'bookDir',
        column: ['name', 'sex', 'phone1', 'phone2', 'phone3', 'phone4', 'phone5', 'phone6'],//
    },
};


export default class SQLite extends Component {
    dbInfo;

    constructor(dbInfo) {
        super();
        this.dbInfo = dbInfo;
        this._open();
    }

    componentWillUnmount() {
        if (this.dbInfo.db) {
            this.dbInfo.db.close();
            this.dbInfo.db = null;
            Log.log('SQLiteStorage Close');
        } else {
            Log.log("SQLiteStorage not open");
        }
    }

    _open = () => {
        if (!this.dbInfo.db) {
            this.dbInfo.db = SQLiteStorage.openDatabase(
                this.dbInfo.database_name,
                this.dbInfo.database_version,
                this.dbInfo.database_displayname,
                this.dbInfo.database_size,
                () => {
                    Log.log('SQLiteStorage open');
                }, (err) => {
                    Log.log('SQLiteStorage_open_err:', err);
                });
            this._createTable(this.dbInfo.table0);
        }
    };

    _createTable = (table) => {
        //创建用户表
        this.dbInfo.db.transaction((tx) => {
            let column = table.column;
            let result = '';
            for (let i = 0; i < column.length; i++) {
                result += column[i] + ' varchar,'
            }
            result = result.substr(0, result.length - 1);
            tx.executeSql('CREATE TABLE IF NOT EXISTS ' + table.name
                + '(' + 'id INTEGER PRIMARY KEY  AUTOINCREMENT,' + result + ')',
                [],
                () => {
                    Log.log('创建表成功executeSql');
                }, (err) => {
                    Log.log('创建表错误_executeSql:', err);
                });
        }, (err) => {
            //所有的 transaction都应该有错误的回调方法，在方法里面打印异常信息，不然你可能不会知道哪里出错了。
            Log.log('创建表错误_transaction:', err);
        }, () => {
            Log.log('创建表成功transaction');
        })
    }

    _deleteDB = () => {
        this._open();
        this.dbInfo.db.transaction((tx) => {
            tx.executeSql('delete from user', [], () => {
                Log.log('执行语句成功executeSql');
            }, (err) => {
                Log.log('执行语句错误_executeSql:', err);
            });
        });
    }

    _dropTable() {
        this.dbInfo.db.transaction((tx) => {
            tx.executeSql('drop table user', [], () => {
            });
        }, (err) => {
            Log.log('删除表错误_transaction:', err);
        }, () => {
            Log.log('删除表成功transaction');
        });
    }

    _insertUserData = (userData) => {
        let len = userData.length;
        this._open();
        this.dbInfo.db.transaction((tx) => {
            for (let i = 0; i < len; i++) {
                var user = userData[i];
                let name = user.name;
                let sex = user.sex;
                let phone = user.phone;
                let sql = "INSERT INTO user(name,phone) " +
                    "values(?,?)";
                tx.executeSql(sql, [name, phone], () => {

                    }, (err) => {
                        Log.log(err);
                    }
                );
            }
        }, (error) => {
            Log.log('数据插入失败', error);
        }, () => {
            Log.log('成功插入 ' + len + ' 条用户数据');
        });
    }

    _query = (callBack) => {
        this._open();
        this.dbInfo.db.transaction((tx) => {
            tx.executeSql("select * from user", [], (tx, results) => {
                let len = results.rows.length;
                let temp = [];
                for (let i = 0; i < len; i++) {
                    var u = results.rows.item(i);
                    // alert("姓名：" + u.name + "，年龄：" + u.age + "，电话：" + u.phone);
                    temp.push(u);
                }
                callBack(temp);
            });
        }, (error) => {
            Log.log('查询失败:', error);
        });
    }

    _close() {
        if (this.dbInfo.db) {
            Log.log('db_close');
            this.dbInfo.db.close();
        } else {
            Log.log("SQLiteStorage not open");
        }
        this.dbInfo.db = null;
    }


    render() {
        return null;
    }
}
